<template>
  <el-drawer
    :title="mainName"
    size="60%"
    :visible.sync="isShowModal"
    @close="closeDrawer"
  >
    <!-- <div class="app-main-title">
      {{ mainName }}
      <div class="goback" @click="$router.replace(`/venueList/venueList`)">
        <i class="el-icon-refresh-left" /> {{translate('backPage')}}
      </div>
    </div> -->
    <el-form
      ref="form"
      class="doumee-form"
      :model="venueInfo"
      label-width="auto"
      label-suffix="："
      :rules="rules"
    >
      <el-form-item v-if="!id" :label="translate('venueCode')" prop="id">
        <el-input v-model="venueInfo.id" class="w400" />
      </el-form-item>
      <el-form-item :label="translate('venueName')" prop="name">
        <el-input v-model="venueInfo.name" class="w400" />
      </el-form-item>
      <el-form-item :label="translate('venueJc')" prop="simpleName">
        <el-input v-model="venueInfo.simpleName" class="w400" />
      </el-form-item>
      <el-form-item :label="translate('contactPhone')" prop="telephone">
        <el-input
          v-model="venueInfo.telephone"
          class="w400"
          onkeyup="value=value.replace(/[^\d^\.]/g,'')"
        />
      </el-form-item>
      <el-form-item :label="translate('venueLogo')" prop="logo">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="VENUE_IMG"
            :fixed-number="[32, 32]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <div class="df_ac">
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            :data="uploadParam"
            :show-file-list="false"
            accept=".jpg,.png"
            :auto-upload="false"
            :on-change="addFileChange"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="venueInfo.showLogo"
              class="file"
              :style="'background-image: url(' + venueInfo.showLogo + ')'"
            >
              <div class="delete">
                <i class="el-icon-delete icon" @click.stop="deleteImage" />
              </div>
            </div>
          </el-upload>
          <div class="placeholder9">
            <div>{{ translate("jycc") }}：{{ "100px X 100px" }}</div>
            <div>
              {{ translate("zctpsm") }}
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="translate('venuePic')" prop="imageList">
        <el-upload
          :action="uploadFileUrl"
          accept=".jpg,.png"
          list-type="picture-card"
          :file-list="venueInfo.imageList"
          :limit="6"
          :on-success="filesUploadSuccess"
          :on-remove="filesUploadRemove"
          name="file"
          :data="uploadParam"
        >
          <i class="el-icon-plus" />
          <div slot="tip" class="el-upload__tip">
            {{ translate("zctpsm") }},{{ translate("sxlz") }}
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item :label="translate('venueAddr')" prop="provinceName">
        <div class="time-inline">
          <dh-area
            :province="venueInfo.provinceName"
            :city="venueInfo.cityName"
            :area="venueInfo.areaName"
            :province-code="venueInfo.provinceCode"
            :city-code="venueInfo.cityCode"
            :area-code="venueInfo.areaCode"
            @change="handleAreaChange($event, venueInfo)"
          />
          <el-input
            v-model="venueInfo.detailedAddress"
            class="item w400"
            :placeholder="translate('DetailAddr')"
          />
        </div>
      </el-form-item>
      <el-form-item
        v-if="!id"
        :label="translate('venueService')"
        prop="selectCofigList"
      >
        <el-checkbox-group v-model="venueInfo.selectCofigList">
          <el-checkbox
            v-for="(item, index) in venueInfo.facilitys"
            :key="index"
            :label="item.id"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        v-if="id"
        :label="translate('venueService')"
        prop="selectCofigList"
      >
        <el-checkbox-group v-model="venueInfo.selectCofigList">
          <el-checkbox
            v-for="(item, index) in venueInfo.facilitys"
            :key="index"
            :label="item.configId"
            >{{ item.configName }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item :label="translate('venuePosition')" prop="postion">
        <el-input
          v-model="venueInfo.postion"
          class="item"
          type="text"
          disabled
        />
        <span class="item" style="color: #666666"
          >{{ translate("longitude") }}：</span
        >
        <span class="item" style="color: #222222">{{ longitude }}</span>
        <span class="item" style="color: #666666"
          >{{ translate("latitude") }}：</span
        >
        <span class="item" style="color: #222222">{{ latitude }}</span>
      </el-form-item>

      <el-form-item>
        <div class="form-line" />
      </el-form-item>
      <el-form-item>
        <mapDrag class="mapbox" @center="getCenter" />
      </el-form-item>
      <el-form-item :label="translate('sort')" prop="sort">
        <el-input
          v-model="venueInfo.sort"
          class="w400"
          onkeyup="value=value.replace(/[^\d^\.]/g,'')"
          oninput="if(value<=0) { value = ''}"
          :placeholder="translate('sortDesc')"
        />
      </el-form-item>
      <el-form-item>
        <div class="margin-t-20">
          <span style="color: #1943a9; font: 18px Medium">{{
            translate("businessInfo")
          }}</span>
        </div>
      </el-form-item>
      <!-- <div class="property-title" style="width: 100px;text-align: right;">{{translate('businessInfo')}}</div> -->
      <el-form-item
        class=""
        :label="translate('businessHours')"
        prop="openTime"
      >
        <el-time-picker
          v-model="venueInfo.openTime"
          is-range
          class="w400"
          :range-separator="translate('to')"
          :start-placeholder="translate('kssj')"
          :end-placeholder="translate('jssj')"
          :placeholder="translate('xzsjfw')"
          value-format="HH:mm"
          format="HH:mm"
        />
      </el-form-item>
      <el-form-item :label="translate('businessStatus')" prop="openStatus">
        <el-select
          v-model="venueInfo.openStatus"
          class="w400"
          :placeholder="translate('businessStatusPlace')"
        >
          <el-option
            v-for="item in filters.businessStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="translate('venueDesc')">
        <el-input
          v-model="venueInfo.describe"
          :rows="5"
          type="textarea"
          maxlength="400"
          :placeholder="translate('venueDescPlace')"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit('form')"
          >{{ translate("tj") }}</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script>
import { configList, venueInfo, uploadFile, updateVenueInfo, addVenueInfo } from '@/api'

import DhArea from '@/components/DhArea'
import MapDrag from '@/components/Map/mapDrag.vue'
import Cropper from '@/components/cropper'
// import Mapview from '@/components/Amap/MapContainer.vue'
// import mapDrag from '@/components/mapDrag'
export default {
  name: 'VenueEdit',
  components: {
    DhArea,
    MapDrag,
    Cropper
  },
  data() {
    return {
      isShowModal: false,

      subLoading: false,
      optionImg: '',
      fileinfo: {},
      dialogCropperVisible: false,
      param: {},
      id: '',
      mainName: this.translate('venueAdd'),
      imageList: [],
      logoList: [],
      venueInfo: {
        selectCofigList: [],
        facilitys: []
      },
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'VENUE_IMG'
      },
      logo: [],
      filters: {
        venueImageList: [],
        status: '1',
        businessStatus: [
          { value: '1', label: this.translate('normal') },
          { value: '0', label: this.translate('closeDown') }
        ]
      },
      dragData: {
        lng: null,
        lat: null,
        address: null,
        nearestJunction: null,
        nearestRoad: null,
        nearestPOI: null
      },
      form: {},
      rules: {
        id: [
          { required: true, message: this.translate('venueCodePlace'), trigger: 'blur' },
          { pattern: /^\+?[1-9][0-9]*$/, message: this.translate('onlyInputNumber'), trigger: 'blur' }
        ],
        name: [{ required: true, message: this.translate('venueNamePlace'), trigger: 'blur' }],
        simpleName: [
          { required: true, message: this.translate('venueJcPlace'), trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: this.translate('contactPhonePlace'), trigger: 'blur' }
        ],
        logo: [
          { required: true, message: this.translate('venueLogoPlace'), trigger: 'change' }
        ],
        imageList: [
          { required: true, message: this.translate('venuePicPlace'), trigger: 'change' }
        ],
        provinceName: [
          { required: true, message: this.translate('venueAddrPlace'), trigger: 'change' }
        ],
        selectCofigList: [
          { required: true, message: this.translate('venueServicePlace'), trigger: 'change' }
        ],
        sort: [{ required: true, message: this.translate('sortPlace'), trigger: 'blur' }],
        openStatus: [
          { required: true, message: this.translate('businessStatusPlace'), trigger: 'change' }
        ],
        openTime: [
          { required: true, message: this.translate('businessHoursP'), trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    latitude() {
      return this.venueInfo.latitudeLongitude
        ? this.venueInfo.latitudeLongitude.split(',')[0]
        : ''
    },
    longitude() {
      return this.venueInfo.latitudeLongitude
        ? this.venueInfo.latitudeLongitude.split(',')[1]
        : ''
    }
  },
  created() {
    // if (this.$route.query.id) {
    //   this.mainName = '编辑场馆'
    //   this.id = this.$route.query.id
    //   this.getVenueInfo()
    // } else {
    //   this.venueInfo = {
    //     selectCofigList: [],
    //     facilitys: []
    //   }
    //   this.getVenueServiceList()
    // }
  },
  methods: {
    // 获取场馆服务列表
    getVenueServiceList() {
      configList({ param: { type: '3' } }).then((res) => {
        if (res.errorCode !== '000000') return
        this.$set(this.venueInfo, 'facilitys', res.recordList)
      })
    },
    getVenueInfo(id) {
      venueInfo({
        param: { id }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        this.venueInfo = res.record
        const selectCofigList = []
        this.venueInfo.facilitys.forEach((facility) => {
          if (facility.isChosed === 1) {
            selectCofigList.push(facility.configId)
          }
        })
        this.$set(this.venueInfo, 'selectCofigList', selectCofigList)
        this.$set(this.venueInfo, 'openTime', [
          res.record.openTimeStart,
          res.record.openTimeEnd
        ])
        this.showPictures()
      })
    },
    showPictures() {
      const imageList = []
      const showpicture = this.venueInfo.showPictures.split(',')
      const pictures = this.venueInfo.picture.split(',')
      showpicture.forEach((item, index) => {
        imageList.push({
          url: showpicture[index],
          response: {
            insertUrl: pictures[index],
            showUrl: showpicture[index]
          }
        })
      })
      this.filters.venueImageList = pictures
      this.$set(this.venueInfo, 'imageList', imageList)
    },
    closeDrawer() {
      this.isShowModal = false
      this.$emit('close')
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.venueInfo, 'showLogo', config.showUrl)
        this.$set(this.venueInfo, 'logo', config.insertUrl)
        this.dialogCropperVisible = false
        this.$refs.form.clearValidate()
      } else {
        this.$message.error(config.msg || this.translate('scsb'))
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    deleteImage() {
      this.$set(this.venueInfo, 'showLogo', '')
      this.$set(this.venueInfo, 'logo', '')
    },
    // 场馆图片上传成功
    filesUploadSuccess(response, file, fileList) {
      this.filters.venueImageList = []
      fileList.forEach((image) => {
        this.filters.venueImageList.push(image.response.insertUrl)
      })
      this.venueInfo.imageList = fileList
      this.$refs.form.clearValidate()
    },
    // 场馆图片移除
    filesUploadRemove(file, fileList) {
      if (fileList.length === 0) {
        this.filters.venueImageList = []
      } else {
        this.filters.venueImageList = []
        fileList.forEach((obj) => {
          this.filters.venueImageList.push(obj.response.insertUrl)
        })
      }
      console.log(this.filters.venueImageList)
    },
    // 地点选择器
    handleAreaChange(area, obj) {
      this.$set(this.venueInfo, 'provinceName', area[0].value)
      this.$set(this.venueInfo, 'provinceCode', area[0].label)
      this.$set(this.venueInfo, 'cityName', area[1].value)
      this.$set(this.venueInfo, 'cityCode', area[1].label)
      this.$set(this.venueInfo, 'areaName', area[2].value)
      this.$set(this.venueInfo, 'areaCode', area[2].label)
      // this.venueInfo.address = obj.province + obj.city + obj.district
    },
    onSubmit(formName) {
      if (this.id) {
        // 编辑场馆
        const that = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const { filters } = that
            let param = JSON.stringify(that.venueInfo)
            param = JSON.parse(param)
            param.picture = that.filters.venueImageList.join(',')
            param.status = filters.status === '1' ? '1' : '0'
            param.address = param.provinceName + param.cityName + param.areaName
            param.openTimeStart = param.openTime[0]
            param.openTimeEnd = param.openTime[1]
            param.facilitys.forEach((config) => {
              config.isChosed = param.selectCofigList.includes(config.configId)
                ? '1'
                : '0'
            })
            this.subLoading = true
            updateVenueInfo({ param })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.closeDrawer()
                  this.$emit('success')
                  that.$message.success(this.translate('editcg'))
                }
              })
              .catch((er) => {
                this.subLoading = false
                console.log(er)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        // 新增场馆
        const that = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const { filters } = that
            let param = JSON.stringify(that.venueInfo)
            param = JSON.parse(param)
            param.picture = that.filters.venueImageList.join(',')
            param.status = filters.status === '1' ? '1' : '0'
            param.address = param.provinceName + param.cityName + param.areaName
            param.openTimeStart = param.openTime[0]
            param.openTimeEnd = param.openTime[1]
            param.facilitys.forEach((config) => {
              config.configId = config.id
              config.isChosed = param.selectCofigList.includes(config.id)
                ? '1'
                : '0'
            })
            this.subLoading = true
            addVenueInfo({ param })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  that.$message.success(this.translate('addcg'))
                  this.closeDrawer()
                  this.$emit('success')
                }
              })
              .catch((er) => {
                this.subLoading = false
                console.log(er)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    getCenter(data) {
      console.log(data)
      this.$set(this.venueInfo, 'postion', data.address)
      this.$set(this.venueInfo, 'latitudeLongitude', data.lnglat)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;

  &:hover {
    border-color: $menuActive;

    .uploader-icon {
      color: $menuActive;
    }
  }

  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;

      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;

        .icon {
          color: #fff;
        }
      }

      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }

  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}

.app-main-title {
  display: flex;
  align-items: center;

  .goback {
    font-size: 12px;
    color: $menuChildActive;
    padding: 0 15px;
    height: 28px;
    line-height: 28px;
    margin-left: 24px;
    border-radius: 14px;
    border: 1px solid;
    cursor: pointer;

    &:hover {
      background-color: $menuChildActive;
      color: #fff;
    }
  }
}

.mapbox {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
  float: left;
}

.time-inline {
  display: flex;
  align-items: center;
  .item {
    width: 200px;
  }

  .itemw_400 {
    width: 400px;
    margin-right: 10px;
  }

  .line {
    width: 20px;
    margin-left: 20px;
    text-align: center;
  }
}
</style>
